package com.denlaku.longan.core;

import com.denlaku.longan.SpringContext;
import com.denlaku.longan.service.TenantMemberService;
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import org.jspecify.annotations.NonNull;

import java.time.Duration;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

/**
 * @author tianx
 */
public class UserTenantCacheManager {
    private static final Cache<@NonNull Long, ConcurrentMap<Long, Boolean>> CACHE = Caffeine.newBuilder()
            .initialCapacity(10)
            .maximumSize(10000)
            .expireAfterWrite(Duration.ofDays(1))
            .build();

    public static boolean exists(Long tenantId, Long userId) {
        ConcurrentMap<Long, Boolean> map = CACHE.get(userId, key -> new ConcurrentHashMap<>(8));
        return map.computeIfAbsent(tenantId, k -> {
            TenantMemberService tenantMemberService = SpringContext.getBean(TenantMemberService.class);
            return tenantMemberService.exists(tenantId, userId);
        });
    }

}
